package com.zhdl.modules.wallpulley.web.service.impl;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.zhdl.modules.wallpulley.entity.EventRecords;
import com.zhdl.modules.wallpulley.entity.ParameterSettings;
import com.zhdl.modules.wallpulley.entity.QEventRecords;
import com.zhdl.modules.wallpulley.service.TensileDistanceService;
import com.zhdl.modules.wallpulley.service.WallPulleyWarnInfoService;
import com.zhdl.modules.wallpulley.web.req.EventRecordsReq;
import com.zhdl.modules.wallpulley.web.resp.*;
import com.zhdl.modules.wallpulley.web.service.WallPulleyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//import static com.zhdl.modules.wallpulley.web.controller.WallPulleyController.*;

@Slf4j
@Service
public class WallPulleyServiceImpl implements WallPulleyService {

    @Resource
    private TensileDistanceService tensileDistanceService;

    @Resource
    private WallPulleyWarnInfoService wallPulleyWarnInfoService;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public List<EventRecordsResp> findAllEventRecords() {
        List<EventRecords> allEventRecords = tensileDistanceService.findAllEventRecords();
        List<EventRecordsResp> resps = new ArrayList<>();
        for (EventRecords allEventRecord : allEventRecords) {
            EventRecordsResp resp = new EventRecordsResp();
            resp.setId(allEventRecord.getId());
            resp.setModelId(allEventRecord.getModelId());
            resp.setRecordResult(allEventRecord.getRecordResult());
            resp.setCreateDate(allEventRecord.getCreateDate());
            resps.add(resp);
        }
        return resps;
    }

    @Override
    public EventInfoSSeResp findInfoByEventId(int id) {
        EventInfoResp infoByEventId = tensileDistanceService.findInfoByEventId(id);
        EventInfoSSeResp infoSSeResp = new EventInfoSSeResp();
        List<TensileDistanceSseResp> tensileDistanceSseResps = new ArrayList<>();
        for (TensileDistanceResp tensileDistanceResp : infoByEventId.getRespList()) {
            TensileDistanceSseResp tensileDistanceSseResp = new TensileDistanceSseResp();
            int distanceValue = tensileDistanceResp.getDistanceValue();
            int tensileValue = tensileDistanceResp.getTensileValue();
            tensileDistanceSseResp.setDistanceValue((((distanceValue / 10000.00) * 5) / 7));
            tensileDistanceSseResp.setTensileValue(tensileValue / 1000.00);
            tensileDistanceSseResp.setType(tensileDistanceResp.getType());
            tensileDistanceSseResp.setMeasurementId(tensileDistanceResp.getMeasurementId());
            tensileDistanceSseResp.setBattery(tensileDistanceResp.getBattery());
            tensileDistanceSseResp.setNowTime(tensileDistanceResp.getNowTime());
            tensileDistanceSseResp.setNowLongTime(tensileDistanceResp.getNowLongTime());
            tensileDistanceSseResp.setDataPointA(tensileDistanceResp.getDataPointA());
            tensileDistanceSseResp.setDataPointB(tensileDistanceResp.getDataPointB());
            tensileDistanceSseResp.setDataPointC(tensileDistanceResp.getDataPointC());
            tensileDistanceSseResp.setDatePointAChange(tensileDistanceResp.getDatePointAChange());
            tensileDistanceSseResp.setDatePointBChange(tensileDistanceResp.getDatePointBChange());
            tensileDistanceSseResp.setDatePointCChange(tensileDistanceResp.getDatePointCChange());
            tensileDistanceSseResps.add(tensileDistanceSseResp);
        }
        infoSSeResp.setMin(infoByEventId.getMin());
        infoSSeResp.setMax(infoByEventId.getMax());
        infoSSeResp.setAverage(infoByEventId.getAverage());
        infoSSeResp.setResult(infoByEventId.getResult());

        infoSSeResp.setL1ValueNo1(infoByEventId.getL1ValueNo1());
        infoSSeResp.setL1ValueNo2(infoByEventId.getL1ValueNo2());
        infoSSeResp.setL1ValueNo3(infoByEventId.getL1ValueNo3());
        infoSSeResp.setL1ValueNo4(infoByEventId.getL1ValueNo4());
        infoSSeResp.setL2ValueNo1(infoByEventId.getL2ValueNo1());
        infoSSeResp.setL2ValueNo2(infoByEventId.getL2ValueNo2());
        infoSSeResp.setL2ValueNo3(infoByEventId.getL2ValueNo3());
        infoSSeResp.setL2ValueNo4(infoByEventId.getL2ValueNo4());
        infoSSeResp.setL3ValueNo1(infoByEventId.getL3ValueNo1());
        infoSSeResp.setL3ValueNo2(infoByEventId.getL3ValueNo2());
        infoSSeResp.setL3ValueNo3(infoByEventId.getL3ValueNo3());
        infoSSeResp.setL3ValueNo4(infoByEventId.getL3ValueNo4());

        infoSSeResp.setNo_on1(infoByEventId.getNo_on1());
        infoSSeResp.setNo_on2(infoByEventId.getNo_on2());
        infoSSeResp.setNo_on3(infoByEventId.getNo_on3());
        infoSSeResp.setNo_on4(infoByEventId.getNo_on4());
        infoSSeResp.setNo_off1(infoByEventId.getNo_off1());
        infoSSeResp.setNo_off2(infoByEventId.getNo_off2());
        infoSSeResp.setNo_off3(infoByEventId.getNo_off3());
        infoSSeResp.setNo_off4(infoByEventId.getNo_off4());

        infoSSeResp.setRespList(tensileDistanceSseResps);
        return infoSSeResp;
    }

    @Override
    public List<ParameterSettingsResp> findAllParam() {
        List<ParameterSettings> allParameterSettings = tensileDistanceService.findAllParameterSettings();
        List<ParameterSettingsResp> resps = new ArrayList<>();
        for (ParameterSettings allParameterSetting : allParameterSettings) {
            ParameterSettingsResp parameterSettingsResp = new ParameterSettingsResp();
            parameterSettingsResp.setPsId(allParameterSetting.getId());
            parameterSettingsResp.setModelEmpty(allParameterSetting.getModelEmpty());
            parameterSettingsResp.setModelZero(allParameterSetting.getModelZero());
            parameterSettingsResp.setModelName(allParameterSetting.getModelName());
            parameterSettingsResp.setModelSpeed(allParameterSetting.getModelSpeed());
            parameterSettingsResp.setModelDistance(allParameterSetting.getModelDistance());
            resps.add(parameterSettingsResp);
        }
        return resps;
    }

    @Override
    public void saveParamSetting(ParameterSettingsResp parameterSettingsResp) {
        tensileDistanceService.saveParameterSetting(parameterSettingsResp);
    }

    @Override
    public Page<EventRecordsResp> findAllEvents(Pageable pageable) {

        QEventRecords qEventRecords = QEventRecords.eventRecords;

        BooleanBuilder builder = new BooleanBuilder();

        JPAQuery<EventRecordsResp> query = jpaQueryFactory
                .select(Projections.constructor(EventRecordsResp.class,
                        qEventRecords.id,
                        qEventRecords.modelId,
                        qEventRecords.recordResult,
                        qEventRecords.createDate
                ))
                .from(qEventRecords)
                .where(builder);

        long total = query.fetchCount();

        List<EventRecordsResp> fetch = query
                .orderBy(qEventRecords.createDate.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

//        List<EventRecordsResp> responses = new ArrayList<>();
//
//        fetch.forEach(item -> {
//            EventRecordsResp recListResp = new EventRecordsResp();
//            BeanUtil.copyProperties(item, recListResp, CopyOptions.create().setIgnoreNullValue(true));
//            responses.add(recListResp);
//        });

        return new PageImpl<>(fetch, pageable, total);
    }

    @Override
    public void getEventCount(EventListResp eventListResp) {
        int ok = 0, fail = 0;
        List<EventRecordsResp> allEventRecords = findAllEventRecords();
        for (EventRecordsResp allEventRecord : allEventRecords) {
            if (allEventRecord.getRecordResult().equals("合格")) {
                ok++;
            } else if (allEventRecord.getRecordResult().equals("不合格")) {
                fail++;
            }
        }
        eventListResp.setCount(allEventRecords.size());
        eventListResp.setOkResult(ok);
        eventListResp.setFailResult(fail);
    }

    @Override
    public Page<EventRecordsResp> findAllRecords(EventRecordsReq request, Pageable pageable) {

        QEventRecords qEventRecords = QEventRecords.eventRecords;

        BooleanBuilder builder = new BooleanBuilder();

        //查找时间范围段内的信息
        builder.and(qEventRecords.createDate.between(request.getStartTime(), request.getEndTime()));

        JPAQuery<EventRecordsResp> query = jpaQueryFactory
                .select(Projections.constructor(EventRecordsResp.class,
                        qEventRecords.id,
                        qEventRecords.modelId,
                        qEventRecords.recordResult,
                        qEventRecords.createDate
                ))
                .from(qEventRecords)
                .where(builder)
                .leftJoin(qEventRecords).on(qEventRecords.modelId.eq(request.psId));

        long total = query.fetchCount();

        List<EventRecordsResp> all = query.
                orderBy(qEventRecords.createDate.desc())
                .fetch();

        int ok = 0, fail = 0;
        for (EventRecordsResp resp : all) {
            if (resp.getRecordResult().equals("合格")) {
                ok++;
            } else if (resp.getRecordResult().equals("不合格")) {
                fail++;
            }
        }

//        count = (int) total;
//        okResult = ok;
//        failResult = fail;

        List<EventRecordsResp> fetch = query
                .orderBy(qEventRecords.createDate.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

//        List<EventRecordsResp> responses = new ArrayList<>();
//
//        fetch.forEach(item -> {
//            EventRecordsResp recListResp = new EventRecordsResp();
//            BeanUtil.copyProperties(item, recListResp, CopyOptions.create().setIgnoreNullValue(true));
//            responses.add(recListResp);
//        });

//        int ok = 0, fail = 0;
//        for (EventRecordsResp respons : fetch) {
//            if (respons.getRecordResult().equals("合格")) {
//                ok++;
//            } else if (respons.getRecordResult().equals("不合格")) {
//                fail++;
//            }
//        }
//        count = (int) total;
//        okResult = ok;
//        failResult = fail;
//
//        String jsonStr = JSONUtil.toJsonStr(fetch);
//        log.info(jsonStr);

        return new PageImpl<>(fetch, pageable, total);

    }
}
